package ext.tianma.bom.util;

import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;

import com.ptc.core.meta.common.impl.LogicalAttributeFormatException;

import ext.tianma.bom.service.FinishedGoodService;
import wt.csm.navigation.ClassificationNode;
import wt.csm.navigation.ClassificationStruct;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.iba.definition.ReferenceDefinition;
import wt.iba.value.IBAHolder;
import wt.iba.value.IBAReferenceable;
import wt.iba.value.ReferenceValue;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.log4j.LogR;
import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.part.QuantityUnit;
import wt.part.Source;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.pds.StatementSpec;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.type.TypeDefinitionReference;
import wt.type.TypedUtility;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.vc.VersionControlHelper;
import wt.vc.views.ViewHelper;
import wt.vc.views.ViewReference;

public class ClassificationUtil  implements RemoteAccess
{
	private static final Logger log = LogR.getLogger(ClassificationUtil.class.getName());

 // 在类型管理器中自定义的part类型
 private static String part_type = "wt.part.WTPart";
 // 产品中文件夹的路径，注意默认在文件夹前夹上Default
 private static String PartPath = "Default/";

 /**
  * 创建一个新的部件
  * 

  * @param args
  * @throws WTException
  * @throws WTPropertyVetoException
  * @throws InvocationTargetException 
  * @throws RemoteException 
  */
 public static void main(String[] args) throws WTPropertyVetoException, WTException, RemoteException, InvocationTargetException
 {
//	RemoteMethod("0000093842");
	 try {
			RemoteMethodServer rms = RemoteMethodServer.getDefault();
			rms.setUserName("wcadmin");
			rms.setPassword("tmadmin");
//			rms.invoke("getClassificationNode", CreatePart7.class.getName(),null,null,null);
			rms.invoke("newPart", ClassificationUtil.class.getName(),null,null,null);
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
//  WTPart part =RemoteMethod("001", part_type);
//  if(part!=null)
//  {
//   log.info("part 的名称是:"+ part.getName());
//  }
 }

 /**
  * 创建一个新的部件，类似的代码可以实现修改part的基本属性
  * 
  * @param number
  *            部件的编码
  * @param PartType
  *            部件的类型，部件在windchill中可以自定义很多中类型
  * @return
  * @throws WTException
  * @throws WTPropertyVetoException
  */
 public static  QueryResult getQueryResult(Class className,String attribute,String value) throws WTException{
		QueryResult qr = null;
		try {
			QuerySpec qs = new QuerySpec(className);
			SearchCondition sc = new SearchCondition(className,attribute,SearchCondition.EQUAL,value);
			qs.appendWhere(sc);
			qr = PersistenceHelper.manager.find(qs);
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		return qr;
	}
 public static WTPart newPart() throws Exception
 {
  WTPart newPart = null;
  // 获取容器
  WTContainer container = null;
  QueryResult qr = getQueryResult(WTContainer.class, WTContainer.NAME, "物料库");
  while (qr.hasMoreElements())
  {
    container = (WTContainer) qr.nextElement();
  }
 
  // 获取容器的引用
  WTContainerRef ref = ref = WTContainerRef.newWTContainerRef(container);
  // 获取文件夹
  Folder folder = wt.folder.FolderHelper.service.getFolder(PartPath, ref);
 
  String strPartNumber = "testClass002";
  String strPartName = "testClass002";
  wt.vc.views.View view = ViewHelper.service.getView("Design");
  ViewReference viewRef = ViewReference.newViewReference(view);

  TypeDefinitionReference typeDefinitionRef = TypedUtility.getTypeDefinitionReference("wt.part.WTPart|cn.tianma.SemiFinishedGood|cn.tianma.C4");
 
  // 创建一个部件，编码与名称
  newPart = WTPart.newWTPart(strPartNumber, strPartName);
  // 为部件设置容器
  newPart.setContainer(container);
  // 为部件设置类型
  newPart.setTypeDefinitionReference(typeDefinitionRef);
  // 为部件设置view
  newPart.setView(viewRef);
  //是否成品
  newPart.setEndItem(false);
  //设置单位
  QuantityUnit unit = QuantityUnit.toQuantityUnit("PCS");
  newPart.setDefaultUnit(unit);
  //设置来源
	Source source = Source.toSource("make");
	newPart.setSource(source);
  // 为此部件设置存贮位置
  FolderHelper.assignLocation((FolderEntry) newPart, folder);
  // 保存部件，切忌不要保存两次。经常在调用完本方法之后习惯性的再保存一次，这样会出现错误。
  newPart = (WTPart) PersistenceHelper.manager.save(newPart);
  // 从数据库中提取part
  newPart = (WTPart) PersistenceHelper.manager.refresh(newPart);
  setClassification("wt.part.WTPart","C4",newPart);
  newPart = (WTPart) PersistenceHelper.manager.refresh(newPart);
  IBAUtil partIba = new IBAUtil(newPart);
  partIba.setIBAValue("MtlNumofPOLTop", "test007");//对应上POL料号
  //newPart = (WTPart) partIba.updateAttributeContainer(newPart);
  partIba.store(newPart);
  IBAUtil partIba2 = new IBAUtil(newPart);
  log.info("----------Part1:" + partIba2.getIBAValue("MtlNumofPOLTop"));
  log.info("----------Part1:" + partIba2.getIBAValue("Part"));
  return newPart;
 }
 /**
  * 
  * @param classificationType  wt.part.WTPart
  * @param classificationPath  name
  * @param holder pbo
  * @throws Exception
  */
 public static void setClassification(String classificationType,
			String classificationPath, IBAHolder holder) throws Exception {

		ReferenceDefinition refDefinition = getReferenceDefinition(classificationType);
		if (refDefinition == null)
			throw new Exception("No Classification Structure Found for "
					+ classificationType);

		// IBAReferenceable referenceable = getClassificationNodeByPath(
		// classificationType, classificationPath);
		IBAReferenceable referenceable = getClassificationNodeByName(classificationPath);
		if (referenceable == null)
			throw new Exception("No Classification Path " + classificationPath
					+ " found for " + classificationType);

		ReferenceValue refValue = ReferenceValue.newReferenceValue(
				refDefinition, holder, referenceable);
		PersistenceHelper.manager.save(refValue);

	}
	
	public static ClassificationNode getClassificationNodeByName(String classificationPath) throws Exception {
		QuerySpec spec = new QuerySpec(ClassificationNode.class);

		SearchCondition condition = new SearchCondition(
				ClassificationNode.class, ClassificationNode.NAME,
				SearchCondition.EQUAL, classificationPath);
		spec.appendWhere(condition, new int[0]);
		QueryResult result = PersistenceHelper.manager
				.find((StatementSpec) spec);
		while (result.hasMoreElements())
			return (ClassificationNode) result.nextElement();

		return null;
	}
	//wt.part.WTPart
	public static ReferenceDefinition getReferenceDefinition(
			String classificationType) throws Exception {
		QuerySpec spec = new QuerySpec(ClassificationStruct.class);
		SearchCondition condition = new SearchCondition(
				ClassificationStruct.class, ClassificationStruct.CLASS_NAME,
				SearchCondition.EQUAL, classificationType);
		spec.appendWhere(condition, new int[0]);
		QueryResult result = PersistenceHelper.manager
				.find((StatementSpec) spec);
		while (result.hasMoreElements()) {
			ClassificationStruct struct = (ClassificationStruct) result
					.nextElement();
			return struct.getRefDef();
		}
		return null;
	}
 public static String RemoteMethod(String partNumber) throws RemoteException, InvocationTargetException
 {
  String CLASSNAME = (ClassificationUtil.class).getName();
  Class argTypes[];
  Object svrArgs[];
  argTypes = (new Class[]
  { String.class});
  svrArgs = (new Object[]
  { partNumber});
   return (String)RemoteMethodServer.getDefault().invoke("getClassificationNode", CLASSNAME, null, argTypes, svrArgs);
 }
 public static void getClassificationNode() throws WTException, WTPropertyVetoException
 {
	 try {
			WTPart part = getLatestPart(getWTPartMasterBYNumber("0000093842"));
			log.info("classificationNodeStr--------" + getClassification(part));
			ClassificationNode classificationNode = getClassificationNode(part);
			log.info("classificationNode--------" + classificationNode.getIBAReferenceableDisplayString());
//			PartIBAHelper partIba = new PartIBAHelper(part);
//			String classificationNodeStr = partIba.getIBAValue("Part");
//			log.info("classificationNodeStr--------" + classificationNodeStr);//获取到C4
//			log.info("----------Part:" + partIba.getIBAValue("MtlNumofPOLTop"));
//			ClassificationNode classificationNode = getClassificationNodeByName(classificationNodeStr);
//			CSMUtil.removeClassNode(part, classificationNode);
//			part = (WTPart) PersistenceHelper.manager.refresh(part);
//			ClassificationNode classificationNode5 = getClassificationNodeByName("C5");
//			CSMUtil.setClassNode(part, classificationNode5);
//			partIba.setIBAValue("C2MtlNum", "对应C2料号");
//			part = (WTPart) partIba.updateAttributeContainer(part);
//			PartIBAHelper partIba1 = new PartIBAHelper(part);
//			log.info("----------Part1:" + partIba1.getIBAValue("C2MtlNum"));
//			log.info("----------Part1:" + partIba1.getIBAValue("Part"));
//			IBAUtil iba = new IBAUtil(part);
//			log.info("----------Part2:" + iba.getIBAValue("MtlNumofPOLTop"));
//			IBAUtil ibaC = new IBAUtil(classificationNode);
//			Hashtable ht = ibaC.getAllIBAKey(classificationNode);
//
//			java.util.Enumeration enumKey = ht.keys();
//			while (enumKey.hasMoreElements()) {
//				String key = (String) enumKey.nextElement();
//				log.info("key---------" + key);
//				log.info("ht.get(key)---------" + ht.get(key));
//				log.info("ibaC.getIBAValue((String) ht.get(key))---------" + ibaC.getIBAValue((String) ht.get(key)));
//			}
//			Map<String,String> map = ibaC.getAllAttrValue();
//			 for(String key:map.keySet())
//		        {
//		         log.info("Key: "+key+" Value: "+map.get(key));
//		        }
//			log.info("----------对应虚拟POL料号:" + partClassIba.getIBAValue("对应虚拟POL料号"));
//			partClassIba.setIBAValue("对应虚拟POL料号", "testClass");
//			partClassIba.updateIBAHolder(classificationNode);
//			classificationNode = (ClassificationNode) PersistenceHelper.manager.refresh(classificationNode);
//			log.info("------描述信息：" + classificationNode.getIBAReferenceableDisplayString());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 }
 /*
  * 获取部件的分类节点
  */
 @SuppressWarnings("deprecation")
	public static ClassificationNode getClassificationNode(WTPart part) {
		ClassificationNode classNode = null;		
		QuerySpec queryspec;
		try {
			queryspec = new QuerySpec(wt.iba.value.ReferenceValue.class);
			queryspec.appendSearchCondition(new SearchCondition(
			wt.iba.value.ReferenceValue.class,
			"theIBAHolderReference.key", "=", part.getPersistInfo().getObjectIdentifier()));
		
			QueryResult queryresult = PersistenceHelper.manager.find(queryspec);
			while (queryresult.hasMoreElements()) {
				wt.iba.value.ReferenceValue value = (ReferenceValue) queryresult.nextElement();
				Persistable obj = value.getIBAReferenceableReference().getObject();
				if (obj instanceof ClassificationNode) {
					classNode = (ClassificationNode) obj;
				}
			}
		} catch (QueryException e) {
			e.printStackTrace();
		} catch (WTException e) {
		e.printStackTrace();
		}
		return classNode;
	}
 
 /*
  * 获取部件分类节点的全路径名称，包括父节点名 如：电控零部件 \结构件 \成品电控柜  
  */
 @SuppressWarnings("deprecation")
	public static String getClassification(WTPart part) {
		ClassificationNode classNode = null;		
		QuerySpec queryspec;
		try {
			queryspec = new QuerySpec(wt.iba.value.ReferenceValue.class);
			queryspec.appendSearchCondition(new SearchCondition(
			wt.iba.value.ReferenceValue.class,
			"theIBAHolderReference.key", "=", part.getPersistInfo().getObjectIdentifier()));
		
			QueryResult queryresult = PersistenceHelper.manager.find(queryspec);
			while (queryresult.hasMoreElements()) {
				wt.iba.value.ReferenceValue value = (ReferenceValue) queryresult.nextElement();
				Persistable obj = value.getIBAReferenceableReference().getObject();
				if (obj instanceof ClassificationNode) {
					classNode = (ClassificationNode) obj;
				}
			}
		} catch (QueryException e) {
			e.printStackTrace();
		} catch (WTException e) {
		e.printStackTrace();
		}
		
     //Debug.P("--------------------------------->>>>>>>>>>>>>>> classNode : " + classNode);
		String classification = "";
		if(classNode != null)
		{        
	        ClassificationNode parentNode = null;
	    	List<ClassificationNode> classNodeLink = new ArrayList<ClassificationNode>(); //用于存放部件的分类层级
	    	classNodeLink.add(classNode);
	    	//倒序遍历上层分类
	    	while( (parentNode=classNode.getParent()) != null ){
	    		classNodeLink.add(parentNode);
	    		classNode = parentNode;
	    	}	
	
	    	/**
	    	 * 获取完成的分类路径，例如：标准件/紧固件
	    	 */
	    	int linkSize = classNodeLink.size();
	    	StringBuffer classificationBuffer = new StringBuffer("");
	    	
	    	for(int i=linkSize-1; i>=0; i--){
	    		ClassificationNode node = classNodeLink.get(i);
	    		classificationBuffer.append(node.getName());
	    		classificationBuffer.append("/");
	    	}
	    	classification = classificationBuffer.toString();
	    	if(classification.endsWith("/")){
	    		classification = classification.substring(0,classification.length()-1);
	    	}
		}
		return classification;
	}
 /**
	 * 根据part的编号获取对应的WTPartMaster
	 */
	public static WTPartMaster getWTPartMasterBYNumber(String number)
	
	{
		WTPartMaster master = null;
		try{
			
			
			QuerySpec qsMaster = new QuerySpec(WTPartMaster.class);
			SearchCondition sc = new SearchCondition(WTPartMaster.class, WTPartMaster.NUMBER, SearchCondition.EQUAL, number);
			qsMaster.appendSearchCondition(sc);
			QueryResult qrMaster = PersistenceHelper.manager.find(qsMaster);
			if(qrMaster.hasMoreElements()){
				
				master = (WTPartMaster) qrMaster.nextElement();
			}
			
		}catch (WTException e) {
			e.printStackTrace();
		} 
		return master;
		
	}

	/**
	 * 根据WTPartMaster获得最新版WTPart
	 * 
	 */
	public static WTPart getLatestPart(WTPartMaster partMaster)
			throws Exception {
		WTPart part = null;
		if (partMaster != null) {
			QueryResult qr = VersionControlHelper.service
					.allVersionsOf(partMaster);
			if (qr != null && qr.hasMoreElements()) {
				part = (WTPart) qr.nextElement();
			}
		}
		return part;
	}
	/**
	 * 根据part获取分类
	 * 返回分类节点的值（显示名称、key、value）
	 */
	public static List getNodeIBAByPart(WTPart part){
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		ReferenceFactory rf = new ReferenceFactory();
		ClassificationNode node = ClassificationUtil.getClassificationNode(part);
		//out.print("node name:"+node.getName()+"<br/>");
		//out.print("parent node name:"+node.getParent().getName()+"<br/>");
		try {
			Hashtable values = ext.com.iba.IBAUtil.getIBAValues(node);
			Iterator ibaiter = values.keySet().iterator();
			while (ibaiter.hasNext()) {
				String key = ibaiter.next().toString();
				if(values.get(key) !=null && values.get(key) instanceof String){
					HashMap<String, String> ibamap = new HashMap<String, String>();
					String displayname = FinishedGoodService.queryDisplayName(key, "string");
					String value = (String)values.get(key);
					//out.print("node key:"+key+"--value:"+value+"--显示名称："+displayname+"<br/>");
					ibamap.put("displayname", displayname);
					ibamap.put("key", key);
					ibamap.put("value", value);
					list.add(ibamap);
				}
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
		
	}
	
	/**
	 * 根据part获取分类
	 * 返回分类属性的值（显示名称、key、value）
	 */
	public static List<HashMap<String, String>> getNodeIBAByPart2(WTPart part){
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		ReferenceFactory rf = new ReferenceFactory();
		ClassificationNode node = ClassificationUtil.getClassificationNode(part);
		//out.print("node name:"+node.getName()+"<br/>");
		//out.print("parent node name:"+node.getParent().getName()+"<br/>");
		try {
			Hashtable values = ext.com.iba.IBAUtil.getIBAValues(node);
			Iterator ibaiter = values.keySet().iterator();
			while (ibaiter.hasNext()) {
				String key = ibaiter.next().toString();
				if(values.get(key) !=null && values.get(key) instanceof String){
					HashMap<String, String> ibamap = new HashMap<String, String>();
					String displayname = FinishedGoodService.queryDisplayName(key, "string");
					if("".equals(displayname)){
						displayname = FinishedGoodService.queryDisplayName(key, "float");
						if("".equals(displayname)){
							displayname = FinishedGoodService.queryDisplayName(key, "timestamp");
						}
					}
					String value = (String)values.get(key);
					try{
					//	value = (String) LWCUtil.getValue(part, key);
						Object obj = LWCUtil.getValue(part, key);
						if(obj instanceof String){
							value = (String) obj;
						}else if(obj instanceof Float){
							value = Float.toString((Float)obj) ;
							displayname = FinishedGoodService.queryDisplayName(key, "float");
						}else if(obj instanceof Integer){
							value = Integer.toString((Integer)obj) ;
						}
						if(StringUtil.isNullOrEmpty(value)){
							String value2 = "";
							Object obj2 = LWCUtil.getValue(part, "cn.tianma."+key);
							if(obj2 instanceof String){
								value2 = (String) obj2;
							}else if(obj2 instanceof Float){
								value2 = Float.toString((Float)obj2) ;
								displayname = FinishedGoodService.queryDisplayName(key, "float");
							}else if(obj2 instanceof Integer){
								value2 = Integer.toString((Integer)obj2) ;
							}
							
							
							if(!StringUtil.isNullOrEmpty(value2)){
								value = value2;
							}
						}
					}catch(LogicalAttributeFormatException e){
						log.info("====Exception 111111=====");
					}
					log.info("node key:"+key+"--value:"+value+"--显示名称："+displayname+"<br/>");
					ibamap.put("displayname", displayname);
					ibamap.put("key", key);
					ibamap.put("value", value==null?"":value);
					list.add(ibamap);
				}
				
			}
		} catch (Exception e) {
			log.info("====Exception 22222=====");
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
		
	}
	
	/**
	 * 根据分类名称   获取分类属性名称  
	 * 如：
	 * 根据C1 获取
	 * 对应CF料号
	 * 对应LC料号
	 * 对应TFT料号
	 * 返回分类节点的值（显示名称、key、value）
	 */
	public static List getClassificationAttByName(String  nodename){
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		ReferenceFactory rf = new ReferenceFactory();
		ClassificationNode node;
		try {
			node = getClassificationNodeByName(nodename);
			if(node != null){
				Hashtable values = ext.com.iba.IBAUtil.getIBAValues(node);
				Iterator ibaiter = values.keySet().iterator();
				while (ibaiter.hasNext()) {
					String key = ibaiter.next().toString();
					if(values.get(key) !=null && values.get(key) instanceof String){
						HashMap<String, String> ibamap = new HashMap<String, String>();
						String displayname = FinishedGoodService.queryDisplayName(key, "string");
						String value = (String)values.get(key);
						value = (value==null?"":value);
						//out.print("node key:"+key+"--value:"+value+"--显示名称："+displayname+"<br/>");
						ibamap.put("displayname", displayname);
						ibamap.put("key", key);
						ibamap.put("value", value);
						list.add(ibamap);
					}
					
				}
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//out.print("node name:"+node.getName()+"<br/>");
		//out.print("parent node name:"+node.getParent().getName()+"<br/>");
		return list;
		
	}

}


